<?php

namespace app\home\controller;

use think\Controller;
use think\Request;
use think\Cookie;
use app\common\controller\Home;

class Collect extends Home
{
    public function __construct()
    {
        parent::__construct();
        $this->PostModel = model('Post.Post');
        $this->CollectModel = model('User.Collect');
    }

    public function add()
    {
        if ($this->request->isPost()) {

            $postid = $this->request->param('postid', 0);

            $postData = $this->PostModel->find($postid);

            if (!$postData) {
                $this->error('该帖子不存在');
                exit;
            }

            //判断这个人是否有收藏过这个帖子
            $where = [
                'userid' => $this->LoginUser['id'],
                'postid' => $postid
            ];
            $collect = $this->CollectModel->where($where)->find();

            if ($collect) {
                $this->error('你已收藏过此贴,无需重复收藏');
            }

            //组装数据
            $data = [
                'userid' => $this->LoginUser['id'],
                'postid' => $postid,
                'tag' => $postData['title'],
            ];

            $result = $this->CollectModel->validate('common/user/Collect')->save($data);

            if ($result === FALSE) {
                $this->error($this->CollectModel->getError());
                exit;
            } else {
                $this->success('收藏成功');
                exit;
            }
        }
    }
}
